package mobilerobots.pl.mybluetooth;

import java.util.ArrayList;
import java.util.Set;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
	BluetoothAdapter adapter;
	ArrayList<BluetoothDevice> devicesList;
	private final static int REQUEST_ENABLE_BT = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

	    //Register the BroadcastReceiver
	    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
	    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
	    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
	    registerReceiver(actionReceiver, filter);
		// Get the BluetoothAdapter
		adapter =  BluetoothAdapter.getDefaultAdapter();
		if (adapter == null) {
			Toast.makeText(this, "Device does not support Bluetooth", Toast.LENGTH_LONG).show();
		}	    
        turnOnBluetooth();
	}// protected void onCreate(Bundle savedInstanceState)

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public void checkBluetoothStatus(View v){
		String status;
		// If Bluetooth is enabled show its name and address
		if (adapter.isEnabled()) {
		    String myBluetoothAddress = adapter.getAddress();
		    String myBluetoothName = adapter.getName();
		    int myBluetoothState = adapter.getState();
		    status = myBluetoothName +": "+ myBluetoothAddress +": "+myBluetoothState;			
		}
		// If Bluetooth is disabled send request to enable it through the system settings
		else {
			turnOnBluetooth();
			status = "Try to enable Bluetooth";
		}
		Toast.makeText(this, status, Toast.LENGTH_LONG).show();
	}// public void checkBluetoothStatus(View v)
	
	private void turnOnBluetooth() {
	    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
	}
	
    public void searchPairedBluetoothDevices(View v){
    	Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
    			// If there are paired devices
    			if (pairedDevices.size() > 0) {
    			  for (BluetoothDevice device : pairedDevices) {
    			    Toast.makeText(this, device.getName()+ ": " + device.getAddress(), Toast.LENGTH_LONG).show();
    			  }
    			} 	    	
    }//  public void searchBluetoothDevices(View v)
    
    public void MakeOurBluetoothDiscoverable(View v){
    	if (adapter == null) {
    		  Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_LONG).show();
    		  finish();
    		  return;
    	}
    	else {
    		  Intent intent = new
    		  Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    		  //By default, the device will become discoverable for 120 seconds, however we can increase this period by EXTRA_DISCOVERABLE_DURATION - 200 sec 
    		  intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200);
    		  startActivity(intent);
    	}
    }// public void MakeOurBluetoothDiscoverable
	
    private final BroadcastReceiver actionReceiver = new BroadcastReceiver(){  
        @Override
	        public void onReceive(Context context, Intent intent) {
	            try{
	                String action = intent.getAction();
	                // When discovery finds a device
	                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
	                    // Get the BluetoothDevice object from the Intent
	                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);	                    
	                    devicesList.add(device);
	                }
	                // When discovery is started
	                else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
	                	Toast.makeText(getApplicationContext(), "Discovery Started", Toast.LENGTH_LONG).show();
	                }
	                // When discovery is finished
	                else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
	                	showDevicesList();
	                	Toast.makeText(getApplicationContext(), "Discovery Finished", Toast.LENGTH_LONG).show();
	                } 
	            }
	            catch(Exception e){
	            	System.out.println ( "Broadcast Error : " + e.toString() );
	            }
	        }//  public void onReceive(Context context, Intent intent) 
    	};

    public void searchBluetoothDevices(View v){
    	devicesList = new ArrayList<BluetoothDevice>();
		adapter.cancelDiscovery();
		adapter.startDiscovery();
	}
    
    private void showDevicesList(){       
    	if (devicesList.size() > 0) {
    		  for (BluetoothDevice device : devicesList) {
    		    Toast.makeText(this, device.getName()+ ": " + device.getAddress(), Toast.LENGTH_LONG).show();
    		  }
    	}
    	else{
    		 Toast.makeText(this, "No devices on the list!", Toast.LENGTH_LONG).show();
    	}
    }// private void showDevicesList()

}// public class MainActivity extends Activity
